package com.muc.util;

import java.sql.*;

public class DBUtil {

    private static final String MYSQL_USERNAME = "root";
    private static final String MYSQL_PASSWORD = "Voilet112ARC!";
    private static final String MYSQL_DATABASE_SERVER = "localhost:3306";
    private static final String MYSQL_DATABASE_NAME = "rentalstoremuc";

    private static Connection con;

    static {
        try {
//            Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://" + MYSQL_DATABASE_SERVER + "/" + MYSQL_DATABASE_NAME;
            try {
                con = DriverManager.getConnection(url, MYSQL_USERNAME, MYSQL_PASSWORD);//写在这里，只获取一次，所以要最后关闭
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("student: Add the MySQL jar file to your build path!");
        }
    }

    //获取数据库链接
    public static Connection getConnection() {
        return con;
    }

    public static void close() {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeConn(Connection connection){
        if(connection!=null){
            try {
                connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    public static void closePs(PreparedStatement ps){
        if(ps!=null){
            try {
                ps.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
    public static void closeRs(ResultSet rs){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
